# /**
# * Copyright (c) 2022 Beijing Jiaotong University
# * PhotLab is licensed under [Open Source License].
# * You can use this software according to the terms and conditions of the [Open Source License].
# *
# * You may obtain a copy of [Open Source License] at: [https://open.source.license/]
# *
# * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# *
# * See the [Open Source License] for more details.
# */
# /**
# * Author: Shihao Xie
# * Created: Aug. 3, 2023
# * Supported by: National Key Research and Development Program of China
# */
import os
from phot_server.core.api_injector import api
from phot_server.rpc.main_service.Main import Processor
from phot_server.server_config.global_config import global_config_dict, set_root_config, LOG_FILE_ROOT
from phot_server.server_config.minio_config import minio_config_dict
from phot_server.utils.phot_logger import get_log_file_end


class MainService:
    """
    该服务是pyphot-server相关服务，可以获取pyphot-server的信息和设置服务全局变量
    调用该服务前，请确认已经做过连接服务相关操作并成功连接。例如：

    Examples:
        >>> from thrift import Thrift
        >>> from thrift.transport import TSocket
        >>> from thrift.transport import TTransport
        >>> from thrift.protocol import TBinaryProtocol
        >>> from photlab.main_service.Main import Client as main_client
        >>> transport = TSocket.TSocket("localhost", 8080)
        >>> transport_protocol = TTransport.TBufferedTransport(transport)
        >>> protocol_factory = TBinaryProtocol.TBinaryProtocol(transport_protocol)
        >>> main_client = main_client(protocol_factory)
        >>> transport.open()

    具体使用可以查看测试用例 test/test_interface/test_main.py
    """

    def __init__(self):
        self.server_config_dict = {}
        self.server_config_dict.update(global_config_dict)
        self.server_config_dict.update(minio_config_dict)
        self.log_file_pointer = {"phot_server": get_log_file_end("phot_server"),
                                 "root": get_log_file_end("root"),
                                 "phot": get_log_file_end("phot"),
                                 "phot_engine": get_log_file_end("phot_engine")}

    @api(Processor.process_get_server_version)
    def get_server_version(self):
        """
        获取服务端版本。

        Args:

        Returns:
            String: 服务端版本

        Raises:
            PhotError: 异常代码查看PhotError的exception_code

        Examples:
            >>> main_client.get_server_version()
            >>> 1.0.0.1
        """
        return self.server_config_dict["SERVER_VERSION"]

    @api(Processor.process_get_server_variables)
    def get_server_variables(self):
        """
        获取服务端参数。

        Args:

        Returns:
            Map<String,String>: 服务端参数

        Raises:
            PhotError: 异常代码查看PhotError的exception_code

        Examples:
            >>> main_client.get_server_variables()
            >>> {'IP': '127.0.0.1', 'PORT': '8080', 'PROTOCOL':'TBinaryProtocol', ...}
        """
        variables = {}
        for key, value in self.server_config_dict.items():
            variables[str(key)] = str(value)
        return variables

    @api(Processor.process_set_server_variable)
    def set_server_variable(self, variable, value):
        """
        设置服务端参数。目前只可以修改临时文件存放位置。

        Args:
            variable(String): 参数名称
            value(String): 参数值
        Returns:
            bool: 是否修改成功

        Raises:
            PhotError: 异常代码查看PhotError的exception_code

        Examples:
            >>> main_client.set_server_variable("TEMP_ROOT", "D:/pyphot_server/temp/")
            >>> True
        """
        if os.path.exists(value) is False:
            os.makedirs(value)
        set_root_config(variable, value)
        return True

    @api(Processor.process_get_server_log)
    def get_server_log(self, max_log_num, logger="root"):
        """
        获取服务端日志。

        Args:
            max_log_num(String): 获取的日志最大数量
            logger(String): 日志器名称 {"root", "phot", "phot_engine"}

        Returns:
            list<string>: 日志列表

        Raises:S
            PhotError: 异常代码查看PhotError的exception_codeS

        Examples:
            >>> main_client.get_server_log(10, "root")
        """
        log_list = []
        log_file = open(os.path.join(LOG_FILE_ROOT, logger + ".log"), "r", encoding="utf-8")
        log_file.seek(0, 2)
        eof = log_file.tell()
        log_file.seek(self.log_file_pointer[logger])
        for count in range(0, max_log_num):
            line = log_file.readline()

            if line != "":
                log_list.append(line)
            else:
                break
        self.log_file_pointer[logger] = log_file.tell()
        log_file.close()
        return log_list
